import base64
import json
import pickle

from django import http
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection
from rest_framework import status
from rest_framework.response import Response

from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet
from fjr.models import SKU


# 购物车数据获取添

class ShoppingcartAddView(View):
    def post(self, request):
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 判断参数是否齐全
        if not all([sku_id, count]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断sku_id是否存在
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品不存在')
        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseForbidden('参数count有误')
        # 判断selected是否为bool值
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')
        # 判断用户是否登录
        if request.user.is_authenticated:
            # 用户已登录，操作redis购物车
            redis_conn = get_redis_connection('carts')
            pipe = redis_conn.pipeline()
            # 新增购物车数据
            pipe.hincrby('carts_%s' % request.user.id, sku_id, count)
            # 新增选中的状态
            if selected:
                pipe.sadd('selected_%s' % request.user.id, sku_id)
            # 执行管道
            pipe.execute()

            # 响应结果
            return http.JsonResponse({'code': 0,
                                      'errmsg': '添加购物车成功'})
        else:
            # 用户未登录，操作cookie购物车
            cookie_cart = request.COOKIES.get('carts')
            # 如果用户操作过 cookie 购物车
            if cookie_cart:
                # 将 cookie_cart 转成 base64 的 bytes,最后将 bytes 转字典
                cart_dict = pickle.loads(base64.b64decode(cookie_cart))
            else:
                # 用户从没有操作过 cookie 购物车
                cart_dict = {}
        if sku_id in cart_dict:
            # 累加求和
            count += cart_dict[sku_id]['count']

        cart_dict[sku_id] = {
            'count': count,
            'selected': selected
        }
        # 将字典转成 bytes,再将 bytes 转成 base64 的 bytes
        # 最后将bytes转字符串
        cart_data = base64.b64encode(pickle.dumps(cart_dict)).decode()
        # 创建响应对象
        response = http.JsonResponse({'code': 0,
                                      'errmsg': '添加购物车成功'})
        # 响应结果将购物车数据写入到 cookie
        response.set_cookie('carts', cart_data)

        return response

    def get(self, request):
        user = request.user
        # 判断用户是否登录
        # 用户登录查询Redis购物车
        if user.is_authenticated:
            # 查询Redis数据库
            redis_data = get_redis_connection('carts')
            # 获取Redis购物车数据
            redis_dict = redis_data.hgetall('carts_%s' % user.id)
            # 获取Redis中的选中状态
            cart_selected = redis_data.smembers('selected_%s' % user.id)
            cart_dict = {}
            for sku_id, count in redis_dict.items():
                cart_dict[int(sku_id)] = {
                    "count": int(count),
                    "selected": sku_id in cart_selected
                }

        # 用户未登录，查询cookies购物车
        else:
            cookie_cart = request.COOKIES.get('carts')
            if cookie_cart:
                cart_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))
            else:
                cart_dict = {}
        sku_ids = cart_dict.keys()
        skus = SKU.objects.filter(id__in=sku_ids)
        cart_skus = []
        for sku in skus:
            cart_skus.append({
                    'id': sku.id,
                    'name': sku.name,
                    'price': sku.price,
                    "default_image": sku.default_image.url,
                    'count': cart_dict.get(sku.id).get('count'),
                    'selected': cart_dict.get(sku.id).get('selected')
                })
        print(cart_skus)
        return JsonResponse(cart_skus, safe=False)
# # 购物车记录修改

# class ShoppingcartModifyView(APIView):
    def put(self, request):
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        count = json_dict.get('count')
        selected = json_dict.get('selected', True)

        # 判断参数是否齐全
        if not all([sku_id, count]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断sku_id是否存在
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品不存在')
        # 判断count是否为数字
        try:
            count = int(count)
        except Exception:
            return http.HttpResponseForbidden('必传参数有误')
        # 判断selected是否为bool值
        if selected:
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('必传参数有误')
        # 判断用户是否登录
        user = request.user
        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            pipe = redis_conn.pipeline()
            pipe.hset('carts_%s' % user.id, sku_id, count)
            # 是否选中
            if selected:
                pipe.sadd('selected_%s' % user.id, sku_id)
            else:
                pipe.srem('selected_%s' % user.id, sku_id)
            pipe.execute()
            # 创建响应对象
            cart_sku = {
                "id": sku_id,
                "count": count,
                "selected": selected
            }
            return JsonResponse(cart_sku)
        else:
            cookie_cart = request.COOKIES.get('carts')
            if cookie_cart:
                cart_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))
            else:
                cookie_cart = {}
            cart_dict[sku_id] = {
                "count": count,
                "selected": selected
            }
            cart_data = base64.b64encode(pickle.dumps(cart_dict)).decode()
            # 创建响应对象
            cart_sku = {
                "id": sku_id,
                "count": count,
                "selected": selected
            }
            response = JsonResponse(cart_sku)
            response.set_cookie("carts", cart_data)
            return response

# 购物车记录删除
# class ShoppingcartDeleteView(APIView):
    def delete(self, request):
        json_dict = json.loads(request.body.decode())
        sku_id = json_dict.get('sku_id')
        try:
            SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('商品不存在')
        user = request.user
        # 判断用户是否登录
        if user is not None and user.is_authenticated:
            # 用户登录操作Redis
            redis_conn = get_redis_connection('carts')
            pipe = redis_conn.pipeline()
            pipe.hdel("carts_%s" % user.id, sku_id)
            pipe.srem("selected_%s" % user.id, sku_id)
            pipe.execute()
            return http.JsonResponse({'code': 0,
                                      'errmsg': '删除购物车成功'})
        else:
            # 用户未登录操作cookie
            cookie_cart = request.COOKIES.get('carts')
            if cookie_cart:
                cart_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))
            else:
                cart_dict = {}
            response = http.JsonResponse({'code': 0,
                                          'errmsg': '删除购物车成功'})

            if sku_id in cart_dict:
                del cart_dict[sku_id]
                cart_data = base64.b64encode(pickle.dumps(cart_dict)).decode()
                response.set_cookie("carts", cart_data)
            return response


#  购物车全选和取消全选
class ShoppingcartChooseView(View):
    def put(self, request):
        json_dict = json.loads(request.body.decode())
        selected = json_dict.get("selected", True)
        # 效验数据
        if selected:
            # 检验数据是否是布尔值
            if not isinstance(selected, bool):
                return http.HttpResponseForbidden('参数selected有误')
        user = request.user
        # 判断是否登录用户
        if user.is_authenticated:
            redis_conn = get_redis_connection('carts')
            redis_dict = redis_conn.hgetall('carts_%s' % user.id)
            sku_ids = redis_dict.keys()

            if selected:
                redis_conn.sadd("selected_%s" % user.id, *sku_ids)
            else:
                redis_conn.srem('selected_%s' % user.id, *sku_ids)
            return http.JsonResponse({'code': 0,
                                      'errmsg': '全选购物车成功'})
        else:
            cookie_cart = request.COOKIES.get('carts')
            response = http.JsonResponse({'code': 0,
                                          'errmsg': '全选购物车成功'})
            if cookie_cart:
                cart_dict = pickle.loads(base64.b64decode(cookie_cart.encode()))
                for sku_id in cart_dict.keys():
                    cart_dict[sku_id]['selected'] = selected
            cart_data = base64.b64encode(pickle.dumps(cart_dict)).decode()
            response.set_cookie('carts', cart_data)
            return response












